<template>
	<view class="page">
		<!-- 年月选择器 - 提升优先级 -->
		<MonthPickerPopup ref="datePickerRef" @confirm="handleDateConfirm" @cancel="handleMonthCancel"
			style="z-index: 9999;" type="datetime" />
		<view class="bgColor">
			<image src="/static/mine/mineBg.png" mode=""></image>
		</view>
		<cusHeaderVue titleContent="物料详情" :showBack="true"></cusHeaderVue>
		<scroll-view scroll-y="true"
			:style="{paddingTop: `calc(${scrollerHeight} + 90rpx)`,height: `calc(100vh - ${scrollerHeight} - 90rpx`}">
			<view class="contBox">
				<view v-if="isLoading" class="loadingBox">
					加载中...
				</view>
				<view v-else class="contLi">
					<view class="contTop">
						<view class="contName">
							领取物品:{{materialDetail.name || ''}}
						</view>
						<view v-if="materialDetail.status === 0" class="contStatus">
							待审批
						</view>
						<view v-else-if="materialDetail.status === 1" class="contStatus contStatusOne">
							待收货
						</view>
						<view v-else-if="materialDetail.status === 2" class="contStatus contStatusTwo">
							待投放
						</view>
						<view v-else-if="materialDetail.status === 3" class="contStatus contStatusThree">
							投放完毕
						</view>
					</view>
					<view class="contTip">
						申请人：<text>{{materialDetail.nickName || ''}}</text>
					</view>
					<view class="contTip">
						申请时间：<text>{{formatTime(materialDetail.createTime)}}</text>
					</view>
					<view v-if="materialDetail.reviewerTime" class="contTip">
						审批时间：<text>{{formatTime(materialDetail.reviewerTime)}}</text>
					</view>
					<view class="contTip">
						数量：<text>{{materialDetail.num || 0}}</text>
					</view>
					<view class="contTip">
						剩余数量：<text>{{(materialDetail.num || 0) - (materialDetail.ylNum || 0)}}</text>
					</view>
					<view class="contTip">
						事由：<text>{{materialDetail.reasonStr || ''}}</text>
					</view>
					<view class="contTip">
						价格：<text>¥{{materialDetail.price || '0.00'}}</text>
					</view>
				</view>
				<view class="contLi">
					<view class="contTop">
						<view class="contName">
							投放记录
						</view>
					</view>
					<view class="contStep">
						<view v-if="putRecords.length === 0" class="emptyBox">
							暂无投放记录
						</view>
						<view class="contStepLi" v-for="(item,index) in putRecords" :key="index">
							<view class="contStepTop">
								<view class="contStepLiDianBox">
									<view class="contStepLiDian">
									</view>
								</view>
								<view class="contStepLiTime">
									{{formatTime(item.createTime)}}
								</view>
							</view>
							<view class="contStepTextBig">
								<view class="contStepText">
									<view class="contStepTextLi">
										投放人：<text>{{item.nickName || ''}}</text>
									</view>
									<view class="contStepTextLi">
										投放数量：<text>{{item.num || 0}}</text>
									</view>
									<view class="contStepTextLi">
										投放门店：<text>{{item.shopName || item.storeName || ''}}</text>
									</view>
									<view class="contStepTextLi">
										投放时间：<text>{{item.deliveryTime || ''}}</text>
									</view>
								</view>

							</view>
						</view>
					</view>
				</view>


			</view>
		</scroll-view>
		<view v-if="showActionButtons" class="btnBox">
			<view v-if="materialDetail.status === 1" class="btnLi" @click="confirmReceipt">
				确认收货
			</view>
			<view v-else-if="materialDetail.status === 2" class="btnLi" @click="putIn">
				投放
			</view>

		</view>

		<u-popup :safeAreaInsetBottom="false" :show="show" :round="13" mode="center" :z-index="10071" :closeable="true"
			@close="close">
			<view class="popupBox">
				<view class="popupLi" style="margin-top: 0;">
					<view class="popupName">
						投放数量
					</view>
					<view class="popupRight">
						<u-number-box :min="1" :max="maxDeliveryNum" v-model="deliveryNum"></u-number-box>
						<view class="popupNum">
							剩余：{{maxDeliveryNum}}
						</view>
					</view>
				</view>
				<view class="popupLi" @click="selectShop">
					<view class="popupName">
						投放门店
					</view>
					<view class="popupInpt">
						<view class="popupInptText" :class="shop?'popupInptTextA':''">
							{{shop?shop:"请选择投放门店"}}
						</view>
						<u-icon name="arrow-down" color="#babac2" size="18"></u-icon>
					</view>
				</view>
				<view class="popupLi" @click="openDatePicker">
					<view class="popupName">
						投放时间
					</view>
					<view class="popupInpt">
						<view class="popupInptText" :class="time?'popupInptTextA':''">
							{{time?time:"请选择投放时间"}}
						</view>
						<u-icon name="arrow-down" color="#babac2" size="18"></u-icon>
					</view>
				</view>
				<view class="popupBtn" @click="confirmDelivery">
					确认投放
				</view>
			</view>
		</u-popup>



		<!-- 已移除日期选择器组件 -->
	</view>
</template>

<script setup>
	import {
		onLoad,
	} from '@dcloudio/uni-app';
	import {
		ref,
		computed
	} from 'vue';
	import cusHeaderVue from '@/components/cus-header.vue';
	import MonthPickerPopup from '@/components/MonthPickerPopup.vue';
	import {
		GETMaterialDetail,
		CREATE_MATERIAL_DELIVERY,
		CONFIRM_MATERIAL_ORDER,
		GETMyShops
	} from '@/api/interface.js';
	const scrollerHeight = ref('');
	const shop = ref(''); //投放门店
	const time = ref(''); //请选择投放时间
	const show = ref(false);
	const materialDetail = ref({}); //物料详情
	const putRecords = ref([]); //投放记录
	const isLoading = ref(true);
	const deliveryNum = ref(1); // 投放数量
	const shopId = ref(''); // 门店ID
	const shopsList = ref([]); // 门店列表
	const datePickerRef = ref(null); // 日期选择器引用
	const selectedYear = ref(new Date().getFullYear());
	const selectedMonth = ref(new Date().getMonth() + 1);
	// 已移除日期选择器相关变量

	// 计算是否显示操作按钮
	const showActionButtons = computed(() => {
		return materialDetail.value.status === 1 || materialDetail.value.status === 2;
	});

	// 计算最大投放数量（总数量减去已使用数量）
	const maxDeliveryNum = computed(() => {
		return (materialDetail.value.num || 0) - (materialDetail.value.ylNum || 0);
	});
	const close = () => {
		show.value = false
	}

	const putIn = () => {
		deliveryNum.value = 1; // 重置投放数量
		shop.value = ''; // 重置门店
		shopId.value = ''; // 重置门店ID
		time.value = ''; // 重置时间
		show.value = true;
	};

	// 确认收货
	const confirmReceipt = async () => {
		// 显示确认提示框，防止误触
		uni.showModal({
			title: '确认收货',
			content: '确定要确认收货吗？此操作不可撤销。',
			success: async (res) => {
				// 只有用户点击确定时才调用接口
				if (res.confirm) {
					try {
						isLoading.value = true;
						const result = await CONFIRM_MATERIAL_ORDER({
							id: materialDetail.value.id
						});
						if (result.code === 0) {
							uni.showToast({
								title: '确认收货成功',
								icon: 'success'
							});
							// 刷新数据
							loadMaterialDetail(materialDetail.value.id);
						} else {
							uni.showToast({
								title: result.message || '确认收货失败',
								icon: 'none'
							});
						}
					} catch (error) {
						console.error('确认收货失败:', error);
						uni.showToast({
							title: '网络异常，请稍后重试',
							icon: 'none'
						});
					} finally {
						isLoading.value = false;
					}
				}
				// 用户点击取消时不执行任何操作
			}
		});
	};

	// 获取门店列表
	const loadShopsList = async () => {
		try {
			const res = await GETMyShops();
			if (res.code === 0 && res.data) {
				shopsList.value = res.data;
				console.log('门店列表数据:', res.data);
			} else {
				console.error('获取门店列表失败:', res.message);
				shopsList.value = [];
			}
		} catch (error) {
			console.error('获取门店列表异常:', error);
			shopsList.value = [];
		}
	};

	// 选择门店
	const selectShop = async () => {
		// 先加载门店列表
		await loadShopsList();

		if (shopsList.value.length === 0) {
			return uni.showToast({
				title: '暂无可用门店',
				icon: 'none'
			});
		}

		// 提取门店名称列表
		const shopNames = shopsList.value.map(item => item.name || '未知门店');

		uni.showActionSheet({
			itemList: shopNames,
			success: (res) => {
				const selectedShop = shopsList.value[res.tapIndex];
				shop.value = selectedShop.name || '未知门店';
				shopId.value = String(selectedShop.id || '');
				console.log('选择的门店:', {
					name: shop.value,
					id: shopId.value
				});
			},
			fail: (err) => {
				console.log('取消门店选择:', err);
			}
		});
	};

	// 计算指定年月的天数
	const getDaysInMonth = (year, month) => {
		return new Date(year, month, 0).getDate();
	};

	// 更新月份天数
	const updateDaysInMonth = (year, month) => {
		// 简化实现，仅用于计算当前月的天数
		const days = getDaysInMonth(year, month);
		return days;
	};

	// 处理日期时间选择确认（兼容 年月日、年月 以及 年月日 时:分:秒）
	const handleDateConfirm = (dateStr) => {
		const str = String(dateStr || '');
		const mDateTime = str.match(/(\d{4})年(\d{1,2})月(\d{1,2})日\s+(\d{1,2}):(\d{1,2}):(\d{1,2})/);
		const mDate = str.match(/(\d{4})年(\d{1,2})月(\d{1,2})日/);
		const mMonth = str.match(/(\d{4})年(\d{1,2})月/);
		const pad2 = (n) => ('0' + n).slice(-2);
		if (mDateTime) {
			const [_, y, mo, d, h, mi, s] = mDateTime;
			selectedYear.value = parseInt(y);
			selectedMonth.value = parseInt(mo);
			time.value = `${y}-${pad2(mo)}-${pad2(d)} ${pad2(h)}:${pad2(mi)}:${pad2(s)}`;
		} else if (mDate) {
			const [_, y, mo, d] = mDate;
			selectedYear.value = parseInt(y);
			selectedMonth.value = parseInt(mo);
			time.value = `${y}-${pad2(mo)}-${pad2(d)}`;
		} else if (mMonth) {
			const [_, y, mo] = mMonth;
			selectedYear.value = parseInt(y);
			selectedMonth.value = parseInt(mo);
			// 使用当前日并做边界保护
			const today = new Date().getDate();
			const daysInMonth = getDaysInMonth(selectedYear.value, selectedMonth.value);
			const day = Math.min(today, daysInMonth);
			time.value = `${y}-${pad2(mo)}-${pad2(day)}`;
		} else {
			console.warn('未能解析日期:', dateStr);
		}
		// 重新显示投放弹窗
		setTimeout(() => {
			show.value = true;
		}, 100);
	};

	// 处理年月选择取消
	const handleMonthCancel = () => {
		// 重新显示投放弹窗
		setTimeout(() => {
			show.value = true;
		}, 100);
	};

	// 打开日期选择器
	const openDatePicker = () => {
		try {
			// 先隐藏投放弹窗，避免遮挡年月选择器
			show.value = false;
			// 延迟打开年月选择器，确保投放弹窗完全隐藏
			setTimeout(() => {
				if (datePickerRef.value && typeof datePickerRef.value.open === 'function') {
					datePickerRef.value.open();
				} else {
					console.warn('日期选择器未初始化完成');
					// 如果日期选择器未初始化，恢复显示投放弹窗
					show.value = true;
				}
			}, 100);
		} catch (error) {
			console.error('打开日期选择器失败:', error);
			// 发生错误时恢复显示投放弹窗
			show.value = true;
		}
	};

	// 将选择的日期补全为当前时分秒，返回 YYYY-MM-DD HH:mm:ss
	const getFullDeliveryTime = (dateStr) => {
		if (!dateStr) return '';
		// 如果已有时间部分，则直接返回
		if (/\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}/.test(dateStr) || dateStr.includes(':')) {
			return dateStr;
		}
		const now = new Date();
		const hh = String(now.getHours()).padStart(2, '0');
		const mm = String(now.getMinutes()).padStart(2, '0');
		const ss = String(now.getSeconds()).padStart(2, '0');
		return `${dateStr} ${hh}:${mm}:${ss}`;
	};

	// 确认投放
	const confirmDelivery = async () => {
		// 验证表单
		if (!deliveryNum.value || deliveryNum.value <= 0) {
			return uni.showToast({
				title: '请输入有效的投放数量',
				icon: 'none'
			});
		}
		if (deliveryNum.value > maxDeliveryNum.value) {
			return uni.showToast({
				title: '投放数量不能超过剩余数量',
				icon: 'none'
			});
		}

		if (!shopId.value) {
			return uni.showToast({
				title: '请选择投放门店',
				icon: 'none'
			});
		}

		if (!time.value) {
			return uni.showToast({
				title: '请选择投放时间',
				icon: 'none'
			});
		}

		try {
			isLoading.value = true;
			const res = await CREATE_MATERIAL_DELIVERY({
				num: String(deliveryNum.value),
				claimId: String(materialDetail.value.id),
				shopId: String(shopId.value),
				materialsId: String(materialDetail.value.materialsId),
				deliveryTime: getFullDeliveryTime(time.value)
			});

			if (res.code === 0) {
				uni.showToast({
					title: '投放成功',
					icon: 'success'
				});
				show.value = false; // 投放成功时关闭弹窗
				// 只有投放成功时才刷新数据
				loadMaterialDetail(materialDetail.value.id);
			} else {
				uni.showToast({
					title: res.message || '投放失败',
					icon: 'none'
				});
				// 投放失败时不关闭弹窗，不刷新数据，保持当前状态，方便用户修改参数重试
			}
		} catch (error) {
			console.error('投放失败:', error);
			uni.showToast({
				title: '网络异常，请稍后重试',
				icon: 'none'
			});
			// 网络异常时不关闭弹窗，不刷新数据，保持当前状态
		} finally {
			isLoading.value = false;
		}
	};


	//获取状态栏高度
	const getBarHeight = () => {
		uni.getSystemInfo({
			success: function(res) {
				scrollerHeight.value = res.statusBarHeight + 'px'
			}
		});
	}

	const toUrl = (urlSrc) => {
		uni.navigateTo({
			url: urlSrc
		})
	}

	// 格式化时间戳
	const formatTime = (timestamp) => {
		if (!timestamp) return '';
		const date = new Date(timestamp);
		const year = date.getFullYear();
		const month = String(date.getMonth() + 1).padStart(2, '0');
		const day = String(date.getDate()).padStart(2, '0');
		const hours = String(date.getHours()).padStart(2, '0');
		const minutes = String(date.getMinutes()).padStart(2, '0');
		const seconds = String(date.getSeconds()).padStart(2, '0');
		return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
	}
	// 获取物料详情数据
	const loadMaterialDetail = async (id) => {
		try {
			isLoading.value = true;
			const res = await GETMaterialDetail({
				id
			});
			if (res.code === 0 && res.data) {
				console.log(res.data)
				console.log(res.data)
				materialDetail.value = res.data;
				// 假设返回的数据中包含投放记录，如果结构不同需要调整
				putRecords.value = res.data.dxMaterialsDeliveryDOS || [];
			} else {
				uni.showToast({
					title: res.message || '获取详情失败',
					icon: 'none'
				});
			}
		} catch (error) {
			console.error('获取物料详情失败:', error);
			uni.showToast({
				title: '网络异常，请稍后重试',
				icon: 'none'
			});
		} finally {
			isLoading.value = false;
		}
	}

	onLoad((options) => {
		getBarHeight();
		if (options.id) {
			loadMaterialDetail(options.id);
		}
	})
</script>

<style lang="scss" scoped>
	.content {
		width: 100%;
		height: 100vh;
	}

	.bgColor {
		width: 100%;
		height: 100vh;
		position: absolute;
		z-index: -1;
		top: 0;

		image {
			width: 100%;
			height: 100%;
		}
	}

	.loadingBox,
	.emptyBox {
		text-align: center;
		padding: 100rpx 0;
		color: #999;
		font-size: 28rpx;
	}

	.contBox {
		padding: 22rpx;
		box-sizing: border-box;
		padding-bottom: calc(env(safe-area-inset-bottom) + 101rpx);

		.contLi {
			border-radius: 12.82rpx 12.82rpx 12.82rpx 12.82rpx;
			background: #ffffff;
			box-shadow: 0 3.85rpx 13.46rpx 0 #b6b7b933;
			margin-bottom: 20rpx;
			padding: 37rpx 27rpx;

			box-sizing: border-box;
		}

		.contTop {
			display: flex;
			align-items: center;
			justify-content: space-between;

			margin-bottom: 20rpx;

			.contName {
				font-weight: 500;
				font-size: 33.33rpx;
				color: #1C2027;
			}

			.contStatus {
				border-radius: 7.69rpx 7.69rpx 7.69rpx 7.69rpx;
				background: #fbe8eb;
				font-size: 24.36rpx;
				font-weight: 400;
				color: #E53251;
				padding: 8rpx 11rpx;
				box-sizing: border-box;
			}

			.contStatusOne {
				background: #fff4d1;
				color: #F79816;
			}

			.contStatusTwo {
				background: #e0eeff;
				color: #3C8CE7;
			}

			.contStatusThree {
				background: #d3f5ec;
				color: #28B08A;
			}
		}

		.contTip {
			color: #7f8494;
			font-weight: 400;
			font-size: 25.64rpx;
			line-height: 48.72rpx;

			text {
				color: #262627;
			}
		}

		.contStep {
			.contStepLi {
				.contStepTop {
					display: flex;
					align-items: center;

					.contStepLiDianBox {
						width: 29rpx;
						height: 29rpx;
						background: rgba(40, 176, 137, 0.16);
						display: flex;
						align-items: center;
						justify-content: center;
						border-radius: 50%;

						.contStepLiDian {
							width: 18rpx;
							height: 18rpx;
							background: #28b089;
							border-radius: 50%;
						}
					}

					.contStepLiTime {
						font-size: 25.64rpx;
						font-weight: 400;
						color: #7F8494;
						margin-left: 19rpx;
					}


				}

				.contStepTextBig {
					border-left: 1px solid #DADCE1;
					padding: 17rpx 30rpx 50rpx;
					box-sizing: border-box;
					margin-left: 14.5rpx;

					.contStepText {
						width: 100%;
						border-radius: 12.82rpx 12.82rpx 12.82rpx 12.82rpx;
						background: #f7f8fa;
						padding: 25rpx 27rpx;
						box-sizing: border-box;

						.contStepTextLi {
							color: #7f8494;
							font-weight: 400;
							font-size: 24.36rpx;
							line-height: 42.31rpx;

							text {
								color: #262627;
							}
						}
					}
				}

			}

			.contStepLi:last-child {
				.contStepTextBig {
					border: none;
				}
			}
		}
	}

	.btnBox {
		display: flex;
		align-items: center;
		justify-content: center;
		position: fixed;
		// bottom: calc(env(safe-area-inset-bottom) + 20rpx);
		bottom: 0;
		width: 100%;
		left: 0;
		padding: 20rpx 55rpx calc(env(safe-area-inset-bottom) + 20rpx);
		box-sizing: border-box;
		background: #f2f3f5;

		.btnLi {
			height: 80rpx;
			border-radius: 40.38rpx 40.38rpx 40.38rpx 40.38rpx;
			background: linear-gradient(-90deg, #feaf38, #f98434);
			box-shadow: 0 3.85rpx 4.49rpx 0 #f984344d;
			color: #ffffff;
			width: 512.82rpx;

			font-size: 32.05rpx;
			font-weight: 400;
			display: flex;
			align-items: center;
			justify-content: center;
		}


	}

	.popupBox {
		width: 644rpx;
		border-radius: 12.82rpx 12.82rpx 12.82rpx 12.82rpx;
		background: #ffffff;
		box-shadow: 2.56rpx 4.49rpx 10.9rpx 0.64rpx #c0c0c03b;
		padding: 60rpx 40rpx;
		box-sizing: border-box;

		.popupLi {
			display: flex;
			align-items: center;
			margin-top: 40rpx;

			.popupName {
				font-weight: 500;
				font-size: 26.92rpx;
				color: #1C2027;
				margin-right: 27rpx;
			}

			.popupRight {
				display: flex;
				align-items: center;

				.popupNum {
					font-weight: 500;
					font-size: 26.92rpx;
					color: #FF2A2A;
					margin-left: 27rpx;
				}
			}

			.popupInpt {
				height: 77rpx;
				border-radius: 10.26rpx 10.26rpx 10.26rpx 10.26rpx;
				background: #f4f6f991;
				display: flex;
				align-items: center;
				padding: 0 17rpx;
				box-sizing: border-box;
				flex: 1;

				.popupInptText {
					font-size: 24.36rpx;
					font-weight: 400;
					color: #7F8494;
					flex: 1;
				}

				.popupInptTextA {

					color: #000000;
				}
			}
		}

		.popupBtn {
			width: 435.9rpx;
			height: 83.33rpx;
			border-radius: 41.67rpx 41.67rpx 41.67rpx 41.67rpx;
			background: linear-gradient(90deg, #feaf38, #f98434);
			font-size: 32.05rpx;
			font-weight: 400;
			color: #FFFFFF;
			display: flex;
			align-items: center;
			justify-content: center;
			margin: 57rpx auto 0;
		}
	}
</style>